<template>
  <el-card class="box-card" shadow="never">
    <div slot="header" class="clearfix">
      <div class="head-container">
        <div class="table_title">方案项目列表</div>
        <div class="btn">
          <el-button
            type="primary"
            size="mini"
            style="margin-right: 5px"
            @click="addPlan"
            >新增</el-button
          >
          <el-button
            type="primary"
            size="mini"
            style="margin-right: 5px"
            @click="savePlan"
            :disabled="!(tableArr && tableArr.length > 0)"
            >保存</el-button
          >
        </div>
      </div>
    </div>
    <el-dialog
      append-to-body
      :close-on-click-modal="false"
      :before-close="cancel"
      :visible.sync="visible"
      title="新增方案项目"
      width="570px"
    >
      <div class="search">
        <el-input
          v-model="formData.treatmentNameOrRef"
          @keyup.enter.native="searchBtn"
          placeholder="治疗项目"
        />
        <el-button type="primary" @click="searchBtn" style="margin-left: 5px"
          >查询</el-button
        >
      </div>
      <el-table
        ref="table"
        v-loading="tableLoading"
        :data="tableList"
        row-key="treatmentId"
        @selection-change="selectionChangeHandler"
        style="width: 100%"
      >
        <el-table-column label="序号" width="60px" prop="indexNumber">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="治疗项目" prop="treatmentName" />
        <el-table-column label="项目类别" prop="dicItemCategoryName" />
        <el-table-column
          type="selection"
          width="55"
          :reserve-selection="true"
        />
      </el-table>
      <el-pagination
        :page-size.sync="page.size"
        :page-sizes="[10, 20, 30, 50]"
        :total="page.total"
        :current-page.sync="page.page"
        style="margin-top: 8px"
        layout="total, prev, pager, next, sizes, jumper"
        @size-change="sizeChangeHandler($event)"
        @current-change="pageChangeHandler"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitClick">确认</el-button>
      </div>
    </el-dialog>
    <el-table ref="table" v-loading="tableArrLoading" :data="tableArr">
      <el-table-column label="序号" width="60px" prop="indexNumber">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="treatmentName" label="治疗项目" />
      <el-table-column prop="dicItemCategoryName" label="项目类别" />
      <el-table-column prop="periodNum" label="疗程次数">
        <template slot-scope="scope">
          <el-input
            placeholder="请输入"
            v-model="tableArr[scope.$index].periodNum"
            type="number"
            min="1"
            @blur="blurInput('periodNum', scope.$index)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="exeInterval" label="执行间隔">
        <template slot-scope="scope">
          <el-input
            placeholder="请输入"
            v-model="tableArr[scope.$index].exeInterval"
            type="number"
            min="1"
            @blur="blurInput('exeInterval', scope.$index)"
          >
            <template slot="append">天</template>
          </el-input>
        </template>
      </el-table-column>
      <el-table-column prop="exePeriod" label="疗程">
        <template slot-scope="scope">
          <el-input
            placeholder="请输入"
            v-model="tableArr[scope.$index].exePeriod"
            type="number"
            min="1"
            @blur="blurInput('exePeriod', scope.$index)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="singleNum" label="单次数量">
        <template slot-scope="scope">
          <el-input
            placeholder="请输入"
            v-model="tableArr[scope.$index].singleNum"
            type="number"
            min="1"
            @blur="blurInput('singleNum', scope.$index)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="delPlan(scope.row.detailId, scope.$index)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </el-card>
</template>

<script>
import {
  getTreatmentProgramme,
  getTreatment,
  delProgramme,
  addProgramme,
} from "@/api/treatmentProject/plans";
export default {
  name: "planItem",
  props: {
    activeRow: {
      type: Object,
      default: null,
    },
  },
  data() {
    return {
      tableLoading: false,
      tableList: [],
      page: {
        // 页码
        page: 1,
        // 每页数据条数
        size: 10,
        // 总数据条数
        total: 0,
      },
      submitLoading: false,
      selections: [],
      visible: false,
      formData: {
        treatmentNameOrRef: null,
      },
      programmeId: undefined,
      tableArr: [],
      tableArrLoading: false,
    };
  },
  watch: {
    activeRow: function (val) {
      if (val) {
        this.programmeId = val.programmeId;
        this.getList();
      }
    },
  },
  mounted() {
    this.getTreatmentList();
  },
  methods: {
    blurInput(label, index) {
      this.tableArr[index][label] = this.tableArr[index][label].replace(
        /^(0+)|[^\d]+/g,
        ""
      );
    },
    getList() {
      getTreatmentProgramme({ programmeId: this.programmeId })
        .then((res) => {
          this.tableArr = res.content;
        })
        .catch((res) => {
          this.$notify({
            title: res.msg,
            type: "error",
            duration: 2500,
          });
        });
    },
    getTreatmentList() {
      this.tableLoading = true;
      getTreatment({
        treatmentNameOrRef: this.formData.treatmentNameOrRef,
        page: this.page.page,
        size: this.page.size,
        sort: "id,desc",
      })
        .then((res) => {
          this.tableList = res.content;
          this.page.total = res.totalElements;
          this.tableLoading = false;
        })
        .catch((res) => {
          this.tableLoading = false;
          this.$notify({
            title: res.msg,
            type: "error",
            duration: 2500,
          });
        });
    },
    searchBtn() {
      this.getTreatmentList();
    },
    selectionChangeHandler(val) {
      this.selections = val;
    },
    //新增
    addPlan() {
      this.visible = true;
    },
    submitClick() {
      let arr = this.tableArr.map((item) => item.treatmentId);
      let arr1 = this.selections.map((item) => item.treatmentId);
      let ids = this.mergeUnique(arr, arr1);
      let diffIds = this.findDifferences(arr, ids);
      let newArr = this.selections.filter((item) =>
        diffIds.includes(item.treatmentId)
      );
      this.tableArr.push(
        ...newArr.map((item) => {
          return {
            ...item,
            singleNum: 1,
          };
        })
      );
      this.cancel();
    },
    mergeUnique(arr1, arr2) {
      return [...new Set([...arr1, ...arr2])];
    },
    findDifferences(arr1, arr2) {
      return [
        ...arr1.filter((item) => !arr2.includes(item)),
        ...arr2.filter((item) => !arr1.includes(item)),
      ];
    },
    cancel() {
      this.visible = false;
      this.$refs.table.clearSelection();
      this.selections = [];
    },
    savePlan() {
      let float = this.tableArr.every((item) => {
        if (!item.periodNum) {
          this.$notify({
            title: "疗程次数不能为空",
            type: "warning",
            duration: 2500,
          });
        } else if (!item.exeInterval) {
          this.$notify({
            title: "执行间隔不能为空",
            type: "warning",
            duration: 2500,
          });
        } else if (!item.exePeriod) {
          this.$notify({
            title: "疗程不能为空",
            type: "warning",
            duration: 2500,
          });
        } else if (!item.singleNum) {
          this.$notify({
            title: "单次数量不能为空",
            type: "warning",
            duration: 2500,
          });
        }
        return (
          item.periodNum && item.exeInterval && item.exePeriod && item.singleNum
        );
      });
      if (float) {
        let treatmentList = this.tableArr.map((item) => {
          return {
            treatmentId: item.treatmentId,
            detailId: item.detailId,
            periodNum: item.periodNum,
            exeInterval: item.exeInterval,
            exePeriod: item.exePeriod,
            singleNum: item.singleNum,
          };
        });
        addProgramme({
          programmeId: this.programmeId,
          treatmentList,
        })
          .then((res) => {
            this.getList();
            this.$notify({
              title: "保存成功",
              type: "success",
              duration: 2500,
            });
          })
          .catch((res) => {
            this.$notify({
              title: res.msg,
              type: "error",
              duration: 2500,
            });
          });
      }
    },
    //删除
    delPlan(id, index) {
      if (id) {
        this.$confirm("是否确定删除该条数据？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          delProgramme({ detailId: id })
            .then((res) => {
              this.$notify({
                title: "删除成功",
                type: "success",
                duration: 2500,
              });
              this.getList();
            })
            .catch((res) => {
              this.$notify({
                title: res.msg,
                type: "error",
                duration: 2500,
              });
            });
        });
      } else {
        this.tableArr.splice(index, 1);
      }
    },
    // 当前页改变
    pageChangeHandler(e) {
      this.page.page = e;
      this.searchBtn();
    },
    // 每页条数改变
    sizeChangeHandler(e) {
      this.page.size = e;
      this.page.page = 1;
      this.searchBtn();
    },
  },
};
</script>

<style lang="scss" scoped>
/deep/.crud-opts {
  display: inline-flex;
}

.table_title {
  display: inline-block;
  line-height: 30px;
  margin: 0 10px 0 0;
  vertical-align: middle;
  font-weight: bold;
  color: #303133;
  font-size: 15px;
}

.head-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 0;
  /deep/.filter-item {
    margin-bottom: 0;
  }
}

.search {
  display: flex;
  margin-bottom: 20px;
}
</style>
